import { ComponentType } from "../component/index";
import { Base } from "../core/Base"
import { browser } from "../core/browser";
import { must,any } from "../core/logic";
import { EventType } from "../event/index";
/**
 * 弹窗类
 * @class
 * @memberof w.info
 */
class Popup extends Base {
  /**
   * @constructor
   * @param {*} opts 
   * @param opts.content {String}【必选】弹窗内容
   * @param opts.mode {String} 【可选,缺省:"multiple"】"multiple":可在多个位置弹出,"single":只能在一个位置弹出。
   */
  constructor(opts = {}) {
    super(opts);
    this.content = document.createElement('div');
    this.content.innerHTML = must(opts.content);
    this.content.style.position = 'absolute';
    this.content.setAttribute('id', this.id);
    this._scene = null;
    this._offsetX = 0;
    this._offsetY = 0;
    this._mode = any(opts.mode, 'multiple');  // single, multiple
    this.anchor = any(opts.anchor,[0,0,0]);
    this.on(EventType.ComponentEvent,(ev)=>{
      if(ev.componentType==ComponentType.Camera){
        this.layout();
      }
    });
  }
  /**
   * @property {String} 弹窗模式。
   */
  set mode(v) {
    this._mode = v;
    return this;
  }

  get mode() {
    return this._mode;
  }
  /**
   * @property {w.Scene} 弹窗的场景。
   */
  set scene(v) {
    this._scene = v;
    return this;
  }

  get scene() {
    return this._scene;
  }

  /**
   * 弹出
   * @method
   */
  show() {
    this.onScene = true;
    this.layout();
    if (this.mode === 'single') {
      this.scene.popups.forEach(popup => {
        if (popup.id === this.id) {
          return true;
        }
        else {
          document.getElementById(popup.id).style.visibility = 'hidden';
        }
      });
    }
  }
  /**
   * 关闭
   * @method
   */
  close() {
    if (this.onScene) {
      this.onScene = false;
      this.content.remove();
    }
  }

  layout() {
    if (this.onScene) {
      let camera = this.scene.getCamera();
      let pixel = camera.worldToPixel(this.anchor);
      if (!document.getElementById(this.id)) {
        this.container.appendChild(this.content);
      }
      this.content.style.visibility = 'visible';
      this.content.style.left = pixel[0] / browser.devicePixelRatio - this._offsetX + 'px';
      this.content.style.top = pixel[1] / browser.devicePixelRatio - this._offsetY + 'px';
    }
  }
  /**
   * 移除
   * @method
   */
  remove() {
    if (this.onScene) {
      this.onScene = false;
      this.content.remove();
    }
  }

  get container() {
    if (this.scene) {
      return this.scene.engine.canvas.parentNode;
    }
  }
}

export {
  Popup
}